var process = require('child_process');
const redis = require('redis');
const koaRedis = require('koa-redis');
const db_conf = require('./db_conf');
const conf = db_conf.redis,
    RDS_PORT = conf.RDS_PORT,                //端口号
    RDS_HOST = conf.RDS_HOST,    //服务器IP  要连接的A服务器redis
    RDS_PWD = conf.RDS_PWD,     //密码
    RDS_OPTS = conf.RDS_OPTS,                  //设置项
    client = redis.createClient(RDS_PORT,RDS_HOST,RDS_OPTS);

client.auth(RDS_PWD,() => {
    console.log('redis 通过认证');
});
client.on('connect',() => {
    console.log('redis connect');
});

const restartRedis = () => {
    process.exec(db_conf.dbShell.startRedis, (error, stdout, stderr) => {
        if (error !== null) {
          console.log('exec error: ' + error);
          restartRedis();
        }
    });
};

client.on('ready',(err) => {
    if (err) {
        restartRedis();
    }
    console.log('redis ready');
});

client.on('error',(err) => {
    console.log('redis error:',err);
    restartRedis();
});
module.exports = koaRedis({client: client, db: 0});